const fs = require('fs-extra')
const path = require('path')
const chalk = require('chalk')
const inquirer = require('inquirer')
const validatePackageName = require('validate-npm-package-name')
const download = require('download-git-repo')
const ora = require('ora')
const url = 'https://gitee.com/anlin/drizzle-demo.git'

/**
 * 
 * 创建项目，并下载模板
 * @parm projectName
 * @param options
 * 
 * **/
async function create(projectName, options) {
    const cwd = options.cwd || process.cwd()
    // 是否在当前目录
    const inCurrent = projectName === '.'
    const name = inCurrent ? path.relative('../', cwd) : projectName
    const targetDir = path.resolve(cwd, projectName || '.')

    const result = validatePackageName(name)
    // 如果所输入的不是合法npm包名，则退出
    if (!result.validForNewPackages) {
        console.error(chalk.red(`不合法的项目名: "${name}"`))
        result.errors && result.errors.forEach(err => {
            console.error(chalk.red.dim('❌ ' + err))
        })
        result.warnings && result.warnings.forEach(warn => {
            console.error(chalk.red.dim('⚠️ ' + warn))
        })
        console.log(chalk.yellow('请使用小写或者-，例如：drizzle-demo'))
        exit(1)
    }
    // 前面完成准备工作，正式开始创建项目
    dwonTem(name, targetDir)
}

// 下载模板
function dwonTem(name, targetDir) {
    const spinner = ora(`正在下载项目模板，源地址：${url}`)
    spinner.start()
    if (fs.existsSync(targetDir)) {
        console.log(chalk.yellow('\n ⚠️该目录已经存在，请更换目录'))
        process.exit(1)
    } else {
        fs.ensureDirSync(name, function (err) {
            console.log(chalk.yellow('\n ⚠️创建目录失败：', err))
            process.exit(1)
        });
        download(`direct:${url}`,
            targetDir,
            { clone: true },
            (err) => {
                if (err) {
                    spinner.fail()
                    console.log(chalk.red("模板下载失败:("))
                } else {
                    spinner.succeed()
                    console.log(chalk.green("模板下载完毕:)"))
                    console.log(chalk.green(`执行： cd ${name} && npm install`))
                }
            }
        )
    }
}
module.exports = (...args) => {
    return create(...args).catch(err => {
        console.log(err)
    })
}